/*
 *  $TEAM_NAME Space Trader
 */
package models;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
import java.util.Observer;
import java.util.Observable;

/**
 * Represents the galaxy that space trader is played in. The galaxy is a singleton.
 * @author bradley
 * @version 1.0
 */
public class Galaxy extends Observable implements Observer {
	/**
	 * field
	 */
	private static Galaxy MY_GALAXY = new Galaxy();
    
	/**
	 * field
	 */
	private final List<StarSystem> systems;

    /**
     * Default constructor 
     */
    private Galaxy() {
       systems = new ArrayList<StarSystem>();

       final BufferedReader reader;

       //Get the list of system names and add them to the galaxy
       try {
           reader = new BufferedReader(new FileReader(
        		   new File("resources/PlanetNames.txt"))); 

           try {
	           String name = reader.readLine();
	           while (name != null) {
	               addSystem(StarSystem.randomStarSystemWithName(name));
	               name = reader.readLine();
	           }
           } catch (Exception e) {
        	   System.err.println(e);
           } finally {
        	   reader.close();
           }
       } catch (Exception e) {
           System.err.println(e);
           System.exit(1);
       }
    }
    
    /**
     * Gets the current galaxy
     * @return the galaxy singleton
     */
    public static Galaxy getGalaxy() {
        if (MY_GALAXY == null) {
        	MY_GALAXY = new Galaxy();
        }
        
        return MY_GALAXY;
    }

    /**
     * Update the observable object
     * @param o - the observable
     * @param arg - the object to update
     */
    public void update(Observable o, Object arg) {
        setChanged();
    }

    /**
     * Adds a star system to the galaxy
     * @param ss - the solar system to add 
     */
    public final void addSystem(StarSystem ss) {
        systems.add(ss);
        setChanged();
    }

    /**
     * Adds a list of system to the galaxy
     * @param moreSystems - the list of solar system
     */
    public void addStarSystems(List<StarSystem> moreSystems) {
        for (StarSystem ss : moreSystems)
            addSystem(ss);
    }

    /**
     * Sets the the sytem list to a new list of systems
     * @param systems - the list of systems
     */
    public void setStarSystems(List<StarSystem> systems) {
        systems.clear();
        addStarSystems(systems);
    }

    /**
     * Gets the current systems
     * @return the list of systems
     */
    public List<StarSystem> getStarSystems() {
        return systems;
    }

    /**
     * Gets a string representation of the galaxy
     * @return the string representation
     */
    public String toString() {
        return "Galaxy";
    }
}
